/**
 * Copyright (c) 2015-2018, Golly Hu 胡高 (3722711@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.hg.jfsa.manage.controller.module.goods;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;

import cn.hg.base.jfinal.controller.BaseController;
import cn.hg.base.kit.StrExtKit;
import cn.hg.jfsa.core.JfsaThreadLocal;
import cn.hg.jfsa.manage.controller.module.goods.validator.AttrCategoryValidator;
import cn.hg.jfsa.manage.web.LayuiPage;
import cn.hg.jfsa.model.AttrCategory;
import cn.hg.jfsa.model.Goods;
import cn.hg.jfsa.model.GoodsType;
import cn.hg.jfsa.model.JfsaAdmin;
import cn.hg.jfsa.web.theme.ThemeManager;

/**
 * @author Golly
 */
public class AttrCategoryController extends BaseController {

	/**
	 * 跳转到新增页面
	 */
	public void add () {
		// 创建一个新的Bean
		this.setAttr("attrCategory", new AttrCategory().setSortNum(0));
		this.setAttr("goodsTypeList", this.getGoodsTypeList());
	}

	/**
	 * Ajax删除功能
	 */
	@Before (EvictInterceptor.class)
	@CacheName ("attrCategory")
	public void ajaxDel () {
		Integer id = this.getParaToInt("id");
		// 通过页面传入的ID查找到记录
		AttrCategory bean = AttrCategory.DAO.findById(id);

		// 记录不存在则报错
		if (null == bean) {
			this.renderAjaxFailed("1", "记录不存在！");
			return;
		}

		// 如果还有任何商品使用此分类，则不允许删除分类
		List<Goods> list =
			Goods.DAO.find("select * from t_goods where type_id = ? and status <> ?", bean.getId(), "del");

		if (list.size() > 0) {
			this.renderAjaxFailed("1", "此分类之下还存在 " + list.size() + " 个商品，不允许删除");
			return;
		}

		// 更新记录的状态为删除
		bean.delete();
		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax方式新建或更新记录
	 */
	@Before ({
		AttrCategoryValidator.class, EvictInterceptor.class
	})
	@CacheName ("attrCategory")
	public void ajaxSaveOrUpdate () {
		// 获取页面传入的Bean
		AttrCategory bean = this.getBean(AttrCategory.class, "attrCategory");
		JfsaAdmin admin = JfsaThreadLocal.getAdmin();
		// 这里引用事务处理是为了方便Ajax模式处理
		Db.tx(new IAtom() {

			@Override
			public boolean run () throws SQLException {

				if (null == bean.getId()) {
					// 新建记录
					bean.setCreatorId(admin.getId())
						.setCreatedTime(new Date())
						.setEditorId(admin.getId())
						.setEditedTime(new Date())
						.save();
				} else {
					// 更新记录
					bean.setEditorId(admin.getId())
						.setEditedTime(new Date())
						.update();
				}

				return true;
			}

		});
		// 返回Ajax成功
		this.renderAjaxSuccessed();
	}

	/**
	 * Ajax方式查询
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("attrCategory")
	public void ajaxSearch () {
		// 建立查询键值对
		Kv para = Kv.by("name", this.getPara("name")).set("goodsTypeId", this.getPara("goodsTypeId"))
			.set("sortField", StrExtKit.humpToUnderline(this.getPara("sortField")))
			.set("sortType", this.getPara("sortType"))
			.set("theme", ThemeManager.me().getCurrentTheme().getId());
		// 通过SQL模板引擎构建SQL及参数
		SqlPara sqlPara = Db.getSqlPara("module.findAttrCategory", para);
		// 执行查询
		Page<AttrCategory> page =
			AttrCategory.DAO.paginate(this.getParaToInt("page"), this.getParaToInt("limit"), sqlPara);
		// 返回Ajax调用的Json结果
		this.renderJson(new LayuiPage(page));
	}

	/**
	 * 跳转到编辑页面
	 */
	public void edit () {
		// 根据ID查找到Bean
		this.setAttr("attrCategory", AttrCategory.DAO.findById(this.getParaToInt("id")));
		this.setAttr("goodsTypeList", this.getGoodsTypeList());
	}

	/**
	 * 跳转到列表页面
	 */
	@Override
	@Before (CacheInterceptor.class)
	@CacheName ("attrCategory")
	public void index () {
		this.setAttr("goodsTypeList", this.getGoodsTypeList());
	}

	/**
	 * 跳转到查看页面
	 */
	@Before (CacheInterceptor.class)
	@CacheName ("attrCategory")
	public void view () {
		this.setAttr("goodsTypeList", this.getGoodsTypeList());
	}

	private List<GoodsType> getGoodsTypeList () {
		List<GoodsType> list = GoodsType.DAO.find("SELECT * FROM t_goods_type ORDER BY sort_num");
		return list;
	}

}
